package com.example.demo.util;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.*;

/**
 * @author zhangfc
 * @date 2022/3/29 16:45
 */
@Component
@EnableScheduling
public class SchedulingDemo implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("demo-pool-%d").build();
        //创建一个大小为5的线程池调度器,默认为单线程.
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5,
                namedThreadFactory);

        taskRegistrar.setScheduler(scheduledThreadPoolExecutor);
        taskRegistrar.addTriggerTask(new Task("test1"), new Trig("0 0/1 8-23 * * ?"));
    }
}

class Task implements Runnable {
    String task;

    public Task(String task) {
        this.task = task;
    }

    @Override
    public void run() {
        System.out.println(task + ":" + LocalDateTime.now() + "," + Thread.currentThread().getName());
    }
}

class Trig implements Trigger {

    private String crontag;

    public Trig(String cron) {
        this.crontag = cron;
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        String cron = null;
        cron = crontag;
        CronTrigger cronTrigger = new CronTrigger(cron);
        return cronTrigger.nextExecutionTime(triggerContext);
    }
}
